package com.timoon.manager.panel.product;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

import org.apache.log4j.Logger;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.tree.Tree;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.slf4j.LoggerFactory;

import com.googlecode.wicket.jquery.ui.Options;
import com.googlecode.wicket.jquery.ui.form.button.AjaxButton;
import com.googlecode.wicket.jquery.ui.panel.JQueryFeedbackPanel;
import com.timoon.app.resource.image.ImageLocation;
import com.timoon.component.panel.editor.EditorPanel;
import com.timoon.component.panel.jlayout.JLayouterPanel;
import com.timoon.sample.dao.model.Product;
import com.timoon.sample.dao.model.ProductInstructionPic;
import com.timoon.sample.dao.model.ProductProperty;
import com.timoon.sample.dao.model.ProductSort;
import com.timoon.sample.utils.SystemConfig;

public class ProductDetailPanel extends Panel {
	
	
	private ProductGridService service;
	
	private Product product;
	
	private ModalWindow win;
	
	private List<ProductProperty> productProperties;
	
	private JQueryFeedbackPanel feedbackPanel;
	
	private FileUploadField photoUpload=null;
	

	public ProductDetailPanel(String id,Product product,ProductGridService service,ModalWindow win) {
		super(id);
		// TODO Auto-generated constructor stub
		
		this.product=product;
		
		this.service=service;
		
		this.productProperties=service.getProductPropertyByProductId(product.getId());
		
		this.win=win;
		
		renderPanel();
	}

	private void renderPanel() {
		// TODO Auto-generated method stub
		
		renderForm();
		
	}

	private void renderForm() {
		// TODO Auto-generated method stub
		Form form=new Form<>("wk_form");
		form.setOutputMarkupId(true);
		add(form);
		
		renderInput(form);
		
		renderButton(form);
		
		renderProductSortTree(form);
		
		renderInstructionImgList(form);//渲染商品说明图片
		
		renderInsImgUploader(form);
		
		renderProperty(form);
		
		renderPhoto(form);
		
		renderFeedback(form);
		
		renderType(form);//商品栏目下拉列表
		
		renderEditor(form);
	}

	private void renderEditor(Form form) {
		// TODO Auto-generated method stub
		
		form.add(new EditorPanel("wk_instruction",new PropertyModel<>(product, "instruction"),false));
	}

	private void renderType(Form form) {
		// TODO Auto-generated method stub
		
		Collection<Integer> typeEntry=SystemConfig.PRODUCT_TYPE_MAP.values();
		List<Integer> types=new ArrayList<Integer>(typeEntry);
		
		final Set<String> typeKeys=SystemConfig.PRODUCT_TYPE_MAP.keySet();
		
		IChoiceRenderer render=new ChoiceRenderer(){
			@Override
			public Object getDisplayValue(Object object) {
				// TODO Auto-generated method stub
				
				String dis="";
				for(String key:typeKeys){
					if(Integer.valueOf(SystemConfig.PRODUCT_TYPE_MAP.get(key).toString()).compareTo(Integer.valueOf(object.toString()))==0){
						dis=key;
					}
				}
				if(dis.equals("")){
					dis="请选择分类";
				}
				
				return dis;
			}
		};
		DropDownChoice<Integer> typeSelect=new DropDownChoice<Integer>("wk_type",  new PropertyModel<Integer>(product, "type"), types,render);
		form.add(typeSelect);
	}

	private void renderFeedback(Form form) {
		// TODO Auto-generated method stub
		feedbackPanel=new JQueryFeedbackPanel("wk_feedback");
		add(feedbackPanel);
	}

	private void renderPhoto(Form form) {
		// TODO Auto-generated method stub
		form.add(new Image("wk_product_photo", new PackageResourceReference(ImageLocation.class,
				this.product.getPhoto())));
		
		photoUpload=new FileUploadField("wk_product_photo_upload");
		form.add(photoUpload);
		
	}

	private void renderProperty(final Form form) {
		// TODO Auto-generated method stub
		
		ListView<ProductProperty> listView=new ListView<ProductProperty>("wk_product_property_list",productProperties) {
			
			@Override
			protected void populateItem(final ListItem<ProductProperty> arg0) {
				// TODO Auto-generated method stub
				ProductProperty pp=arg0.getModelObject();
				arg0.add(new Label("wk_product_property_name",new PropertyModel<>(pp, "name")));
				arg0.add(new Label("wk_product_property_value",new PropertyModel<>(pp, "value")));
				arg0.add(new AjaxLink("wk_product_property_del"){

					@Override
					public void onClick(AjaxRequestTarget target) {
						// TODO Auto-generated method stub
						service.delProductPropertyById(arg0.getModelObject().getId());
						
						target.add(form);
					}
					
				});
			}
		};
		form.add(listView);
		
		final ProductProperty newPP=new ProductProperty();
		newPP.setProductId(product.getId());
		newPP.setStatus(1);
		productProperties.add(newPP);
		
		form.add(new TextField<>("wk_product_property_name_textfield",new PropertyModel<>(newPP, "name")));
		form.add(new TextField<>("wk_product_property_value_textfield",new PropertyModel<>(newPP, "value")));
		form.add(new AjaxButton("wk_product_property_add"){

			@Override
			public void onSubmit(AjaxRequestTarget target,Form form0) {
				// TODO Auto-generated method stub
				service.addProductProperty(newPP);
				
				target.add(form);
				
			}
			
		});
	}

	private void renderInsImgUploader(Form form) {
		// TODO Auto-generated method stub
		final FileUploadField upload=new FileUploadField("wk_ins_img_upload");
		form.add(upload);
		
		form.add(new AjaxButton("wk_ins_img_upload_submit") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				// TODO Auto-generated method stub
				super.onSubmit(target, form);
				
				//System.err.println(ImageLocation.class.getClassLoader().getResource(""));
				StringBuffer path=new StringBuffer(ImageLocation.class.getClassLoader().getResource("com/timoon/app/resource/image/product/").toString());
				FileUpload fileUpload=upload.getFileUpload();
				StringBuffer picName=new StringBuffer(fileUpload.getClientFileName());
				
				//删除path中开头的"file:\"
				String starting=path.substring(6);
				
				
				//截取客户端图片后缀
				String ending=picName.substring(picName.lastIndexOf("."));
				
				//获取系统时间
				String newPicName=String.valueOf((new Date()).getTime())+ending;
				
				String newName=starting+newPicName;
				
				//System.err.println("neName="+newName);
				if(fileUpload!=null){
					try{
						fileUpload.writeTo(new File(newName));
						service.addProductInstructionPic("product/"+newPicName, product.getId());
						
						target.add(form);
					}catch(IOException e){
						e.printStackTrace();
					}
				}
			}
		});
	}

	private void renderInstructionImgList(final Form form) {
		// TODO Auto-generated method stub
		
		List<ProductInstructionPic> pics=this.service.getProductInstructionPicByProductId(product.getId());
		
		ListView<ProductInstructionPic> listView=new ListView<ProductInstructionPic>("wk_instruction_img_list",pics) {
			
			@Override
			protected void populateItem(ListItem<ProductInstructionPic> arg0) {
				// TODO Auto-generated method stub
				final ProductInstructionPic pic=arg0.getModelObject();
				
				arg0.add(new Image("wk_instruction_img", new PackageResourceReference(ImageLocation.class,pic.getPath())));
				arg0.add(new AjaxLink("wk_del_img") {

					@Override
					public void onClick(AjaxRequestTarget target) {
						// TODO Auto-generated method stub
						service.deleteProductInstructionPicById(pic.getId());
						
						StringBuffer path=new StringBuffer(ImageLocation.class.getClassLoader().getResource("com/timoon/app/resource/image/").toString());
						String picName=path+pic.getPath();
						
						File delFile=new File(picName);
						if(delFile.exists()){
							delFile.delete();
						}else{
							
						}
						target.add(form);
					}
				});
			}
		};
		form.add(listView);
	}

	private void renderProductSortTree(Form form) {
		// TODO Auto-generated method stub
		DefaultTreeModel treeModel=this.service.getDefaultTreeModelWithProductSort();
		
		Tree tree=new Tree("wk_sort", treeModel){
			@Override
			protected void onNodeLinkClicked(AjaxRequestTarget target,
					TreeNode node) {
				// TODO Auto-generated method stub
				super.onNodeLinkClicked(target, node);
				ProductSort sort=(ProductSort) ((DefaultMutableTreeNode) node).getUserObject();
				
				product.setSortId(sort.getId());
			}
			@Override
			protected String renderNode(TreeNode node) {
				// TODO Auto-generated method stub
				
				ProductSort sort=(ProductSort) ((DefaultMutableTreeNode) node).getUserObject();
				return sort.getName();
			}
			
		};
		form.add(tree);
	}

	private void renderButton(Form form) {
		// TODO Auto-generated method stub
		form.add(new AjaxButton("wk_submit") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				// TODO Auto-generated method stub
				super.onSubmit(target, form);
				
				boolean isValidation=true;
				
				//如果商品的名字已被改变，则将status置于非0
				if(product.getName().equals("default")){
					isValidation=false;
					feedbackPanel.error("请更改默认的名字");
				}
				
				if(product.getSortId()==null){
					feedbackPanel.error("请选择所属分类");
					isValidation=false;
				}
				
				if(isValidation){
					
					uploadPhoto();
					
					product.setStatus(1);
					service.addProduct(product);
					win.close(target);
					
					updateCenterPanel(target);
				}else{
					target.add(feedbackPanel);
				}
				
				
			}
		});
	}

	private void renderInput(Form form) {
		// TODO Auto-generated method stub
		
		ProductSort sort=this.service.getSortByProductId(product.getSortId());
		
		this.renderTextField("wk_id", "id", product, form);
		this.renderTextField("wk_name", "name", product, form);
		
		this.renderTextField("wk_market_price", "marketPrice", product, form);
		this.renderTextField("wk_actual_price", "actualPrice", product, form);
		this.renderTextArea("wk_sale_info", "saleInfo", product, form);
		//this.renderTextArea("wk_instruction", "instruction", product, form);
		this.renderTextArea("wk_service_info", "serviceInfo", product, form);
		//this.renderTextField("wk_type", "name", product, form);
		this.renderTextArea("wk_pack_list", "packList", product, form);
		this.renderTextArea("wk_service_after_sale", "serviceAfterSale", product, form);
	}
	
	private void renderTextField(String markupId,String exe,Object obj,Form form){
		form.add(new TextField<>(markupId,new PropertyModel<>(obj, exe)));
	}
	private void renderTextArea(String markupId,String exe,Object obj,Form form){
		form.add(new TextArea<>(markupId,new PropertyModel<>(obj, exe)));
	}

	private void uploadPhoto(){
		FileUpload fileUpload=photoUpload.getFileUpload();
		
		if(fileUpload!=null){
			
			String clientName=fileUpload.getClientFileName();
			
			StringBuffer path=new StringBuffer(ImageLocation.class.getClassLoader().getResource("com/timoon/app/resource/image/product/").toString());
			
			//删除path中开头的"file:\"
			String starting=path.substring(6);
			
			//截取客户端图片后缀
			String ending=clientName.substring(clientName.lastIndexOf("."));
			
			//获取系统时间
			String newPicName=String.valueOf((new Date()).getTime())+ending;
			
			try{
				fileUpload.writeTo(new File(starting+newPicName));
				
				product.setPhoto("product/"+newPicName);
			}catch(IOException e){
				e.printStackTrace();
			}
			
		}
	}
	
	private void updateCenterPanel(AjaxRequestTarget arg0){
		JLayouterPanel layouter=(JLayouterPanel) this.getSession().getAttribute("layouter");
		
		layouter.updatePanel(JLayouterPanel.CENTER_PANEL, new ProductGridPanel(JLayouterPanel.CENTER_PANEL), arg0);
	}

}
